package net.cyue.nest.nestjava.common.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

public final class InputUtil {
  private static final int READ_BLOCK_LENGTH = 1024; // 1024 Byte

  public static String readString(InputStream input, Charset charset)
    throws IOException
  {
    StringBuilder builder = new StringBuilder();
    int br = 0;
    byte[] bs = new byte[InputUtil.READ_BLOCK_LENGTH];
    while ((br = input.read(bs)) != -1) {
      String str;
      if (br != bs.length) {
        str = new String(bs, charset);
      } else {
        byte[] newBs =Arrays.copyOfRange(bs, 0, br);
        str = new String(newBs, charset);
      }
      builder.append(str);
    }
    return builder.toString();
  }

  public static String readString(InputStream input)
    throws IOException
  {
    return InputUtil.readString(input, StandardCharsets.UTF_8);
  }

  public static String readString(Reader reader)
    throws IOException
  {
    StringBuilder builder = new StringBuilder();
    int cr = 0;
    char[] cs = new char[InputUtil.READ_BLOCK_LENGTH];
    while((cr = reader.read(cs)) != -1) {
      String str;
      if (cr != cs.length) {
        char[] newCs = Arrays.copyOfRange(cs, 0, cr);
        str = new String(newCs);
      } else {
        str = new String(cs);
      }
      builder.append(str);
    }
    return builder.toString();
  }
}
